const http = require('http');

const options = {
  host: 'localhost',
  port: process.env.PORT || 3000,
  path: '/health',
  timeout: 5000,
  headers: {
    'User-Agent': 'Docker-HealthCheck/1.0'
  }
};

const request = http.request(options, (res) => {
  let data = '';
  
  res.on('data', (chunk) => {
    data += chunk;
  });
  
  res.on('end', () => {
    try {
      const healthData = JSON.parse(data);
      console.log(`健康检查结果: 状态=${res.statusCode}, 运行时间=${Math.floor(healthData.uptime)}秒, 内存=${Math.floor(healthData.memory.rss/1024/1024)}MB`);
      
      if (res.statusCode === 200 && healthData.status === 'ok') {
        // 检查服务是否运行正常
        if (healthData.uptime > 0) {
          process.exit(0);
        } else {
          console.log('服务运行时间异常');
          process.exit(1);
        }
      } else {
        console.log('健康检查失败: 状态不正常');
        process.exit(1);
      }
    } catch (error) {
      console.log('健康检查响应解析失败:', error.message);
      process.exit(1);
    }
  });
});

request.on('error', (err) => {
  console.log('健康检查请求失败:', err.message);
  
  // 根据不同错误类型给出不同退出码
  if (err.code === 'ECONNREFUSED') {
    console.log('服务器拒绝连接');
    process.exit(1);
  } else if (err.code === 'ETIMEDOUT') {
    console.log('健康检查超时');
    process.exit(1);
  } else {
    process.exit(1);
  }
});

request.on('timeout', () => {
  console.log('健康检查超时');
  request.destroy();
  process.exit(1);
});

request.end();